﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace StreamBabyService
{
    public partial class Main : Form
    {

        /// <summary>
        /// Gets the bat path.
        /// </summary>
        /// <value>The bat path.</value>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private string BatPath
        {

            get
            {
                var val = CodeForce.Utilities.RegistryUtility.GetFromRegistry("StreamBabyRunner", "BatPath");
                if (val != null)
                {
                    return val.ToString();
                }
                return string.Empty;
            }
        }
        public StringBuilder Outputdata = new StringBuilder();
        public Main()
        {
            InitializeComponent();


        }

        Process _process = null;
        /// <summary>
        /// Starts the stream baby.
        /// </summary>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void StartStreamBaby()
        {
            if (File.Exists(txtBatFile.Text))
            {
                ThreadPool.QueueUserWorkItem(delegate
                {
                    KillJava();
                    _process = new Process();
                    _process.ErrorDataReceived += ConsoleDataReceived;
                    _process.OutputDataReceived += ConsoleDataReceived;


                    ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", "/c " + txtBatFile.Text);
                    processInfo.CreateNoWindow = true;
                    processInfo.UseShellExecute = false;
                    processInfo.RedirectStandardError = true;
                    processInfo.RedirectStandardOutput = true;
                    _process.StartInfo = processInfo;
                    if (_process.Start())
                    {
                        // Begin async stdout and stderr reading
                        _process.BeginOutputReadLine();
                        _process.BeginErrorReadLine();
                        _process.WaitForExit();

                        _process.Close();

                    }
                });

            }


        }

        /// <summary>
        /// Consoles the data received.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Diagnostics.DataReceivedEventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void ConsoleDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                Outputdata.AppendLine(e.Data);
            }

        }

        /// <summary>
        /// BTNs the open dialog click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void BtnOpenDialogClick(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtBatFile.Text = openFileDialog1.FileName;
            }
        }

        /// <summary>
        /// Form1s the form closing.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosingEventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void Form1FormClosing(object sender, FormClosingEventArgs e)
        {
            Visible = false;
            WindowState = FormWindowState.Minimized;
            e.Cancel = true;
        }

        /// <summary>
        /// Settingses the tool strip menu item click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void SettingsToolStripMenuItemClick(object sender, EventArgs e)
        {
            Visible = true;
            WindowState = FormWindowState.Normal;
        }

        /// <summary>
        /// Exits the tool strip menu item click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void ExitToolStripMenuItemClick(object sender, EventArgs e)
        {

            KillJava();
            notifyIcon1.Dispose();
            Environment.Exit(0);
        }

        /// <summary>
        /// Kills the java.
        /// </summary>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void KillJava()
        {
            try
            {
                if (_process != null)
                {
                    _process.Kill();
                }
                var proc = Process.GetProcessesByName("java");
                foreach (var process in proc)
                {
                    process.Kill();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// BTNs the save settings click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void BtnSaveSettingsClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtBatFile.Text))
            {
                CodeForce.Utilities.RegistryUtility.SaveToRegistry("StreamBabyRunner", "BatPath", txtBatFile.Text);
                //start the bat file
                StartStreamBaby();
            }
        }

        /// <summary>
        /// Views the bat output tool strip menu item click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void ViewBatOutputToolStripMenuItemClick(object sender, EventArgs e)
        {
            BatOutput frm = new BatOutput(Outputdata.ToString(),this);
            frm.Show(this);
        }

        /// <summary>
        /// Form1s the load.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void Form1Load(object sender, EventArgs e)
        {
            txtBatFile.Text = BatPath;
            if (string.IsNullOrEmpty(txtBatFile.Text))
            {
                Visible = true;
                WindowState = FormWindowState.Normal;
            }
            else
            {
                WindowState = FormWindowState.Minimized;
                Visible = false;
                //start the bat file
                StartStreamBaby();
            }
        }

        /// <summary>
        /// Form1s the form closed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosedEventArgs"/> instance containing the event data.</param>
        /// <created on="5/13/2012" by="Dan Turco"/>
        private void Form1FormClosed(object sender, FormClosedEventArgs e)
        {
            KillJava();
        }
    }
}
